//
//  XLCommitPictureView.m
//  XiangLove
//
//  Created by 宋振 on 2018/8/10.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLCommitPictureView.h"

#import "XLCommitPictureCell.h"

#import "XLCollectionViewFlowLayout.h"

#import "XLPersonCenterTool.h"

#import "XLCommitVideoSetModel.h"

#import "BMHPickerView.h"

#import "TQAFNetworkDownload.h"

#import "BMHPhotoPickManager.h"
#import "UIImage+Clip.h"

static NSString *const identifierCell = @"XLCommitPictureCell";

@interface XLCommitPictureView ()<XLCollectionViewFlowLayoutDelegate,UICollectionViewDataSource,UICollectionViewDelegate,BMHPickerViewDelegate>

@property (nonatomic, strong) UICollectionView *  baseCollection;

//图片数量
@property (nonatomic, strong) UILabel *  numberLbl;

//数据源
@property (nonatomic, strong) NSMutableArray *  dataSources;

@end

@implementation XLCommitPictureView
{
    NSIndexPath *_indexPath;
    NSDictionary *changeDic;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self) {
        
        [self initUI];
    }
    
    return self;
}

- (instancetype)init
{
    self = [super init];
    
    if (self) {
        
        self.backgroundColor = [UIColor whiteColor];
        
        [self initUI];
    }
    
    return self;
}


#pragma mark    -   -   -   Init UI -   -   -

/**
 绘制界面显示
 */
- (void)initUI
{
    [self addSubview:self.baseCollection];
    
    [self.baseCollection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).offset(15);
        make.top.equalTo(self.mas_top).offset(15);
        make.right.equalTo(self.mas_right).offset(-15);
        make.bottom.equalTo(self.mas_bottom).offset(-35);
    }];
    
    //注册cell
    [self.baseCollection registerClass:[XLCommitPictureCell class] forCellWithReuseIdentifier:identifierCell];
    
    //说明
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.textAlignment = NSTextAlignmentLeft;
    titleLbl.attributedText = [[NSAttributedString alloc] initWithString:@"点击更换图片, 拖拽可更改排序" attributes:@{
                                                                                                         NSKernAttributeName:@1,
                                                                                                         NSForegroundColorAttributeName:RGB(153, 153, 153),
                                                                                                         NSFontAttributeName:[UIFont fontWithName:kFontNamePFRegular size:12]
                                                                                                         }];
    [self addSubview:titleLbl];
    
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.baseCollection.mas_left);
        make.top.equalTo(self.baseCollection.mas_bottom);
        make.right.lessThanOrEqualTo(@200);
        make.bottom.equalTo(self.mas_bottom);
    }];
    
    //图片数量
    self.numberLbl = [[UILabel alloc] init];
    self.numberLbl.textColor = RGB(153, 153, 153);
    self.numberLbl.textAlignment = NSTextAlignmentRight;
    self.numberLbl.font = [UIFont fontWithName:KFontNamePFMedium size:12];
//    self.numberLbl.text = @"6/8";
    [self addSubview:self.numberLbl];
    
    [self.numberLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleLbl.mas_centerY);
        make.right.equalTo(self.baseCollection.mas_right);
        make.height.mas_equalTo(17);
    }];
}


#pragma mark     - - - 设置代理显示 - - -

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger count = self.dataSources.count > 7 ? 8 : self.dataSources.count+1;
    
    return count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XLCommitPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifierCell forIndexPath:indexPath];
    
    if (self.dataSources.count > indexPath.row) {
        
        
        NSDictionary *dic = self.dataSources[indexPath.row];
        
        cell.dataDic = dic;
        
    }else{
        cell.dataDic = nil;
    }
    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.dataSources.count > indexPath.row) {
        
        _indexPath = indexPath;
        
        //点击图片
        [self setPicturesWithIndexPath:_indexPath];
        
    }else{
        //点击添加图片
        if (self.refreshPictureView) {
            self.refreshPictureView(indexPath, NO);
            
        }
        
        
        
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ((self.dataSources.count-1) == indexPath.row) {
        
        //点击图片
        return NO;
        
    }else{
        //点击添加图片
        return NO;
    }
}

#pragma mark    - - - 设置图片弹窗 - - -

- (void)setPicturesWithIndexPath:(NSIndexPath *)indexPath
{
    NSArray *titleArray;
    if (self.dataSources.count == 1) {
        
        titleArray = @[@"从相册里选",@"拍摄"];
        
    }else{
        titleArray = @[@"设为头像",@"删除",@"从相册里选",@"拍摄"];
    }
    
    
    
    BMHPickerView *pickerView = [[BMHPickerView alloc] initWithTitleArray:titleArray delegate:self];
    [pickerView show];
}



//代理
- (void)pickView:(BMHPickerView *)pickView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    NSInteger select = buttonIndex;
    if (self.dataSources.count == 1) {
        select = buttonIndex+2;
    }
    
    switch (select) {
        case 0:
            {
                
                [self setAvatar];
                
                
                break;
            }
        case 1:
            {
                
                [self deletePic];
                break;
            }
        case 2:
            {
                [self setPicViewWithIndexPath:_indexPath indexSelect:2];
                break;
            }
        case 3:
            {
                [self setPicViewWithIndexPath:_indexPath indexSelect:3];
                break;
            }
            
            
        default:
            break;
    }
}

//设置图片
- (void)setPicViewWithIndexPath:(NSIndexPath *)indexPath indexSelect:(NSInteger)indexSelect
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(commitPicturesReplaceImageWithIndexPath:selectIndex:)]) {
        [self.delegate commitPicturesReplaceImageWithIndexPath:indexPath selectIndex:indexSelect];
    }
}

//设置头像
- (void)setAvatar
{
    NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
    
    //获取数据
    NSDictionary *dict = self.dataSources[_indexPath.row];
    
    NSDictionary *tempDict = @{
                               @"Url":K_DEFULT(dict[@"Url"]),
                               @"UserId":@([NSString stringWithFormat:@"%@",dict[@"UserId"]].integerValue),
                               @"OrderId":@([NSString stringWithFormat:@"%@",dict[@"OrderId"]].integerValue),
                               @"IsHeadImage":@(1),
                               @"Id":@([NSString stringWithFormat:@"%@",dict[@"Id"]].integerValue)
                               };
    
    changeDic = tempDict;
    
    //添加到第一个
    [tempArray addObject:tempDict];
    
    //修改信息
    
    //放在第一位
    
    int i = 0;
    
    for (NSDictionary *dic in self.dataSources) {
        
        if (i == _indexPath.row) {
            i++;
            continue;
        }
        
        NSString *url = K_DEFULT(dic[@"Url"]);
        NSInteger userId = [NSString stringWithFormat:@"%@",dic[@"UserId"]].integerValue;
        NSInteger OrderId = [NSString stringWithFormat:@"%@",dic[@"OrderId"]].integerValue;
        NSInteger IsHeadImage = [NSString stringWithFormat:@"%@",dic[@"IsHeadImage"]].integerValue;
        NSInteger Id = [NSString stringWithFormat:@"%@",dic[@"Id"]].integerValue;
        
        NSDictionary *tempDic = @{
                                  @"Url":url,
                                  @"UserId":@(userId),
                                  @"OrderId":@(OrderId),
                                  @"IsHeadImage":@(0),
                                  @"Id":@(Id)
                                  };
        
        [tempArray addObject:tempDic];
        
        i++;
        
    }
    
    //                [tempArray replaceObjectAtIndex:_indexPath.row withObject:changeDic];
    
    [[TQAFNetworkDownload shareTQAFNetwork] TQAFNetworkHttpRequestJsonStyle:@"POST" Url:@"/Api/v2/UserInfo/UpdateUserPhotos" parameter:@{@"Photos":tempArray} success:^(id responseObject) {
        
        if ([responseObject[@"ApiCode"] isEqualToString:@"Success"]) {
            
            
            if (self.dataSources.count > 0) {
                [self.dataSources removeAllObjects];
            }
            
            self.dataSources = [tempArray mutableCopy];
            
            NSLog(@"上传图片成功");
            self.numberLbl.text = [NSString stringWithFormat:@"%ld/8",self.dataSources.count];
            
            if (self.delegate && [_delegate respondsToSelector:@selector(commitPictureRefreshSource:isRefresh:isMove:)]) {
                [self.delegate commitPictureRefreshSource:self.dataSources isRefresh:NO isMove:NO];
            }
            
            [self.baseCollection reloadData];
            
        }
        
    } failt:^(NSError *error) {
        
        NSLog(@"上传图片失败");
        
    }];
}

//删除图片
- (void)deletePic
{
    //删除 仅剩一张图片是不能删除
    
    if (self.dataSources.count <= 1) {
        
        return;
    }
    
    NSMutableArray *tempArray = [self.dataSources mutableCopy];
    
    [tempArray removeObjectAtIndex:_indexPath.row];
    
    //判断是否还有头像 如果没 设置第一个
    
    BOOL isHave = NO;
    
    for (NSDictionary *dic in tempArray) {
        
        NSInteger isheadImg = [NSString stringWithFormat:@"%@",dic[@"IsHeadImage"]].integerValue;
        
        if (isheadImg ==1) {
            isHave = YES;
            
            break;
        }
        
    }
    
    //如果没有头像了 就设置第一个为头像
    if (isHave == NO) {
        
        NSDictionary *dict = tempArray[0];
        
        NSDictionary *tempDict = @{
                                   @"Url":K_DEFULT(dict[@"Url"]),
                                   @"UserId":@([NSString stringWithFormat:@"%@",dict[@"UserId"]].integerValue),
                                   @"OrderId":@([NSString stringWithFormat:@"%@",dict[@"OrderId"]].integerValue),
                                   @"IsHeadImage":@(1),
                                   @"Id":@([NSString stringWithFormat:@"%@",dict[@"Id"]].integerValue)
                                   };
        
        [tempArray replaceObjectAtIndex:0 withObject:tempDict];
        
    }
    
    
    [[TQAFNetworkDownload shareTQAFNetwork] TQAFNetworkHttpRequestJsonStyle:@"POST" Url:@"/Api/v2/UserInfo/UpdateUserPhotos" parameter:@{@"Photos":tempArray} success:^(id responseObject) {
        
        if ([responseObject[@"ApiCode"] isEqualToString:@"Success"]) {
            
            [self.dataSources removeObjectAtIndex:_indexPath.row];
            
            
            NSLog(@"删除图片成功");
            self.numberLbl.text = [NSString stringWithFormat:@"%ld/8",self.dataSources.count];
            
            if (self.delegate && [_delegate respondsToSelector:@selector(commitPictureRefreshSource:isRefresh:isMove:)]) {
                
                BOOL isRefresh = NO;
                
                if (self.dataSources.count == 3) {
                    isRefresh = YES;
                }
                
                [self.delegate commitPictureRefreshSource:self.dataSources isRefresh:isRefresh isMove:NO];
            }
            
            [self.baseCollection reloadData];
            
        }
        
    } failt:^(NSError *error) {
        
        NSLog(@"上传图片失败");
        
    }];
}




/**** 获取数据 ****/
- (void)setVideos:(NSArray *)videos
{
    _videos = videos;
    
    [self.dataSources addObjectsFromArray:videos];
    
    self.numberLbl.text = [NSString stringWithFormat:@"%ld/8",self.dataSources.count];
    
    [self.baseCollection reloadData];
}


- (CGFloat)getHeaderHeight
{
    [self layoutIfNeeded];
    
    CGFloat height = self.baseCollection.frame.origin.y+self.baseCollection.bounds.size.height+35;
    
    return height;
}

#pragma mark    - - - 懒加载 - - -
/**
 界面容器
 */
- (UICollectionView *)baseCollection
{
    if (!_baseCollection) {
        
        XLCollectionViewFlowLayout * flowLayout = [[XLCollectionViewFlowLayout alloc] init];
        
        flowLayout.delegate = self;
        flowLayout.minimumLineSpacing = 5;
        flowLayout.minimumInteritemSpacing = 7;
        flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 0, 5);
        
        CGFloat itemW = (ScreenWidth-40-3*7)/4;
        
        flowLayout.itemSize = CGSizeMake(itemW, itemW);
        
        self.baseCollection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        self.baseCollection.delegate = self;
        self.baseCollection.dataSource = self;
        self.baseCollection.showsVerticalScrollIndicator = NO;
        self.baseCollection.bounces = NO;
        
        self.baseCollection.backgroundColor = [UIColor whiteColor];
    }
    
    return _baseCollection;
}

- (void)moveItemFromIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    
    if (fromIndexPath.item == self.dataSources.count || toIndexPath.item == self.dataSources.count) {
        return;
    }
    
    [self.dataSources exchangeObjectAtIndex:fromIndexPath.row withObjectAtIndex:toIndexPath.row];
    
    if (self.delegate && [_delegate respondsToSelector:@selector(commitPictureRefreshSource:isRefresh:isMove:)]) {
        [self.delegate commitPictureRefreshSource:self.dataSources isRefresh:NO isMove:YES];
    }

}

////是否可以移动
- (BOOL)isCanMoveItemFromeIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    if ((toIndexPath.row == self.dataSources.count)|| (fromIndexPath.row == self.dataSources.count)) {
        return NO;
    }
    
    return YES;
}

//是否可以选中
- (BOOL)isCanSelectWithIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == self.dataSources.count) {
        return NO;
    }
    
    return YES;
}


#pragma mark    - - - 上传图片方法 - - -

/**
 数据源
 */
- (NSMutableArray *)dataSources
{
    if (!_dataSources) {
        self.dataSources = [NSMutableArray arrayWithCapacity:1];
    }
    
    return _dataSources;
}



@end
